<template>
  <div id="app">
    <router-view v-if="routerAlive" />
  </div>
</template>

<script>
import store from "@/store";
import { removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
export default {
  name: "App",
  provide() {
    return {
      reload: this.reload,
    };
  },

  data() {
    return { routerAlive: true, _beforeUnload_time: 0, _gap_time: 0 };
  },

  methods: {
    //重新加载的方法
    reload() {
      this.routerAlive = false;
      this.$nextTick(function () {
        this.routerAlive = true;
      });
    },
    // 页面关闭之前，触发提示框
    beforeunloadHandler(e) {
      this._beforeUnload_time = new Date().getTime();
      if (e) {
        e = e || window.event;
        console.log(e);
        if (e) {
          e.returnValue = "关闭提示";
        }
      }
    },
    // 页面关闭
    unloadHandler(e) {
      this._gap_time = new Date().getTime() - this._beforeUnload_time;
      //判断是窗口关闭还是刷新
      if (this._gap_time <= 5) {
        //关闭窗口,如果是登录状态 移除用户
        localStorage.clear();
        store.commit("user/SET_TOKEN", "");
        store.commit("user/SET_ROLES", []);
        removeToken();
        resetRouter();
        store.dispatch("tagsView/delAllViews", null, { root: true }); 
      } else {
        // 刷新页面
      }
    },
  },
  mounted() {
    window.addEventListener("beforeunload", (e) => this.beforeunloadHandler(e));
    window.addEventListener("unload", (e) => this.unloadHandler(e));
  },
  destroyed() {
    window.removeEventListener("beforeunload", (e) =>
      this.beforeunloadHandler(e)
    );
    window.removeEventListener("unload", (e) => this.unloadHandler(e));
  },
};
</script>
